#include "sys_work.h"
#include <string.h>

// Maximum number of work items
#define MAX_WORK_ITEMS 8

// Static work item pool
static work_item_type_def work_item_pool[MAX_WORK_ITEMS];

// Initialize work system
void work_system_init(void) {
    // Initialize all work items as inactive
    for (int i = 0; i < MAX_WORK_ITEMS; i++) {
        work_item_pool[i].active = 0;
    }
}

// Find a free work item from the pool
work_item_type_def* work_item_get_free(void) {
    for (int i = 0; i < MAX_WORK_ITEMS; i++) {
        if (work_item_pool[i].active == 0) {
            return &work_item_pool[i];
        }
    }
    return NULL;  // No free work items
}

// Submit a work item to be processed
uint8_t work_submit(work_result (*work_func)(void*), void* param) {
    work_item_type_def* item = work_item_get_free();
    if (item == NULL) {
        return 0;  // No free work items available
    }
    
    // Initialize the work item
    item->work_func = work_func;
    item->param = param;
    item->active = 1;  // Mark as active
    
    return 1;  // Success
}

// Process all active work items
void work_process_all(void) {
    for (int i = 0; i < MAX_WORK_ITEMS; i++) {
        if (work_item_pool[i].active && work_item_pool[i].work_func) {
            work_result result = work_item_pool[i].work_func(work_item_pool[i].param);
            
            // If work is done, deactivate and recycle the work item
            if (result == WORK_DONE) {
                work_item_pool[i].active = 0;
            }
        }
    }
}

// Check if there are any active work items
uint8_t work_has_active_items(void) {
    for (int i = 0; i < MAX_WORK_ITEMS; i++) {
        if (work_item_pool[i].active) {
            return 1;
        }
    }
    return 0;
}

// Get count of active work items
uint8_t work_get_active_count(void) {
    uint8_t count = 0;
    for (int i = 0; i < MAX_WORK_ITEMS; i++) {
        if (work_item_pool[i].active) {
            count++;
        }
    }
    return count;
}

// Work processing task function
void work_processing_task(void) {
    work_process_all();
}